﻿Imports Microsoft.VisualStudio.DebuggerVisualizers
Imports System.Data.Common
Imports System.Data.Objects
Imports System.Data.Objects.DataClasses
Imports System.IO
Imports System.Text

Public Class ObjectContextVisualizerObjectSource
    Inherits VisualizerObjectSource

    '''' <summary>
    '''' </summary>
    '''' <param name="target"></param>
    '''' <param name="outgoingData"></param>
    Public Overrides Sub GetData(ByVal target As Object, ByVal outgoingData As Stream)
        Dim context As ObjectContext = DirectCast(target, ObjectContext)

        Dim ds As New DataSet()

        Dim dt As DataTable = ds.Tables.Add(Constants.TABLE_ENTITIES)
        dt.Columns.Add(Constants.COLUMN_ENTITY).DataType = GetType(String)
        dt.Columns.Add(Constants.COLUMN_UNCHANGED).DataType = GetType(Integer)
        dt.Columns.Add(Constants.COLUMN_MODIFIED).DataType = GetType(Integer)
        dt.Columns.Add(Constants.COLUMN_ADDED).DataType = GetType(Integer)
        dt.Columns.Add(Constants.COLUMN_DELETED).DataType = GetType(Integer)

        Dim entityQuery = From ose In context.ObjectStateManager.GetObjectStateEntries( _
            EntityState.Added Or EntityState.Deleted Or EntityState.Modified Or EntityState.Unchanged) _
                Where ose.Entity IsNot Nothing _
                Group ose By Entity = ose.Entity.ToString() _
                Into Unchanged = Sum(If(ose.State = EntityState.Unchanged, 1, 0)),
                Modified = Sum(If(ose.State = EntityState.Modified, 1, 0)), _
                Added = Sum(If(ose.State = EntityState.Added, 1, 0)), _
                Deleted = Sum(If(ose.State = EntityState.Deleted, 1, 0)) _
                Select Entity, Unchanged, Modified, Added, Deleted _
                Order By Entity

        For Each entity In entityQuery
            dt.Rows.Add(entity.Entity, entity.Unchanged, entity.Modified, entity.Added, entity.Deleted)
        Next

        ds.AcceptChanges()

        ds.WriteXml(outgoingData, XmlWriteMode.WriteSchema)
    End Sub

End Class
